<template>
  <!-- 原生offset -->
  <div class="controller">
    <div id="controller-container" @mousemove="mouseMove">
      <div
        id="controller-ball"
        :style="{ left: cbX + 'px', top: cbY + 'px' }"
        @mouseDown="mouseDown"
        @mouseup="reset"
      ></div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
export default {
  setup() {
    //控制器容器
    let ccDom = null;
    let ccSize = 0;
    //控制器小球
    let cbDom = null;
    let cbSize = 0;
    //用来关联绝对定位的left和top
    let cbX = ref(0);
    let cbY = ref(0);
    onMounted(() => {
      ccDom = document.querySelector("#controller-container");
      ccSize = ccDom.clientWidth;
      console.log("container", { ccSize });
      cbDom = document.querySelector("#controller-ball");
      cbSize = cbDom.clientWidth;
      console.log("Ball", { cbSize });
      cbX.value = ccSize / 2 - cbSize / 2;
      cbY.value = ccSize / 2 - cbSize / 2;
    });

    let isMouseDown = false;
    function mouseMove(e) {
      //仅当在ball上摁下时才允许更新坐标
      if (isMouseDown) {
        //offset是相对当前元素定位
        console.log("鼠标坐标", [e.offsetX, e.offsetY]);
        cbX.value = e.offsetX - cbSize / 2;
        cbY.value = e.offsetY - cbSize / 2;
      }
    }
    function mouseDown() {
      isMouseDown = true;
    }
    function reset() {
      isMouseDown = false;
      //ball位置复位中心处
      cbX.value = ccSize / 2 - cbSize / 2;
      cbY.value = ccSize / 2 - cbSize / 2;
    }

    return { mouseMove, mouseDown, reset, cbX, cbY };
  },
};
</script>
<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.controller {
  height: 100vh;
  background-color: #34495e;
  display: flex;
  justify-content: center;
  align-items: center;
  #controller-container {
    width: 200px;
    height: 200px;
    border: 2px solid #d35400;
    // border-radius: 50%;
    position: fixed;
    left: 80px;
    bottom: 80px;
    #controller-ball {
      width: 50px;
      height: 50px;
      background-color: #2ecc71;
      border-radius: 50%;
      position: absolute;
      transition: 0.04s;
      cursor: pointer;
    }
  }
}
</style>